package com.woniuxy.portal.service.impl;
import java.math.BigDecimal;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.woniuxy.portal.common.constant.RedisConstant;
import com.woniuxy.portal.entity.Book;
import com.woniuxy.portal.model.vo.CartItemVo;
import com.woniuxy.portal.service.IBookService;
import com.woniuxy.portal.service.ICartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

@Service
public class CartServiceImpl implements ICartService {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private IBookService bookService;

    @Override
    public void addCart(Long userId, Long bookId) {
        //1. 先从Redis中获取购物项
        String json = (String) redisTemplate.opsForHash().get(RedisConstant.USER_CART_PREFIX+userId,bookId.toString());

        //2. 判断：是否为空
        CartItemVo cartItemVo = null;
        if (StringUtils.isEmpty(json)) {
            //2.1 如果从Redis中获取的购物项为空，说明第一次添加图书到购物车
            Book book = bookService.getById(bookId);
            cartItemVo = BeanUtil.copyProperties(book,CartItemVo.class);
            // 图书的购买数量，默认是1
            cartItemVo.setBuycount(1);
            // 小计: 第一次购买，金额就是图书的价格
            cartItemVo.setSumPrice(book.getPrice());
        } else {
            //2.2 如果从Redis中获取的购物项不为空, 修改数量+1、小计修改
            // 从redis中获取的购物项json字符串 --->  CartItemVo
            cartItemVo = JSONUtil.toBean(json, CartItemVo.class);
            // 设置购买数量: +1
            cartItemVo.setBuycount(cartItemVo.getBuycount() + 1);
            // 重新计算小计 = 单价 * 数量
            cartItemVo.setSumPrice( cartItemVo.getPrice().multiply( new BigDecimal(cartItemVo.getBuycount()) ));
        }

        // 把CartItemVo对象存储到Redis的Hash类型中
        redisTemplate.opsForHash().put(
                RedisConstant.USER_CART_PREFIX + userId,
                bookId.toString(),
                JSONUtil.toJsonStr(cartItemVo)
        );
    }
}
